<template>
  <div class="p-2">
    <!-- el-form 包裹整个表单 -->
    <div>
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>页面信息</span>
            </div>
          </template>
          <el-form-item label="落地页名称" prop="linkName">
            <el-input v-model="formData.linkName"></el-input>
          </el-form-item>
          <el-form-item label="落地页状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>

        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>页面模式选择</span>
            </div>
          </template>
          <el-form-item label="模式选择" prop="pageMode">
            <el-radio-group v-model="formData.pageMode" @change="getSelectPageMode">
              <el-radio v-for="dict in bus_spread_link_page_mode" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>
        <!--      页面模式选择-->
        <el-card class="box-card" v-if="selectPageMode">
          <template #header>
            <div class="card-header">
              <span>{{selectPageMode?.label}}-{{selectPageMode?.remark}}</span>
            </div>
          </template>
          <!--        图片模式-->
          <image-mode v-if="formData.pageMode === '1001'" ref="imageModeRef" v-model="formData.pageModeContent.image"></image-mode>
          <!--        图文交互模式-->
          <image-text-mode v-if="formData.pageMode === '1002'" ref="imageTextModeRef" v-model="formData.pageModeContent.imageText"></image-text-mode>
          <!--        问答模式-->
          <dialog-mode v-if="formData.pageMode === '1003'" ref="dialogModeRef" v-model="formData.pageModeContent.dialog"></dialog-mode>
          <!--        关键回复模式-->
          <keyword-mode v-if="formData.pageMode === '1004'" ref="keywordModeRef" v-model="formData.pageModeContent.keyword"></keyword-mode>
        </el-card>

        <!--      页面模式设置参数-->
        <el-card class="box-card" v-if="selectPageMode && ['1003','1004'].includes(formData.pageMode || '')">
          <template #header>
            <div class="card-header">
              <span v-if="formData.pageMode === '1003'">问答设置</span>
              <span v-if="formData.pageMode === '1004'">回答内容</span>
            </div>
          </template>
          <!--        问答模式设置-->
          <dialog-set-mode v-if="formData.pageMode === '1003'" ref="dialogSetModeRef" v-model="formData.pageModeContent.dialogSet"></dialog-set-mode>
          <keyword-set-mode v-if="formData.pageMode === '1004'" ref="keywordSetModeRef" v-model="formData.pageModeContent.keywordSet"></keyword-set-mode>
        </el-card>

        <!--      跳转设置-->
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>跳转设置</span>
            </div>
          </template>
          <el-form-item label="跳转模式" prop="skipSet.mode">
            <el-radio-group v-model="formData.skipSet.mode">
              <el-radio value="0">直接跳转</el-radio>
              <el-radio value="1">收集线索后跳转</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="formData.skipSet.mode === '1'">
            <el-form-item label="线索设置" prop="skipSet.collectClue.clueForms">
              <div style="width: 800px;background: #F7F7F7;padding: 20px;">
                <div style="font-size: 10px; color: #999;background-color: white;padding: 10px;">
                  <!-- 表格 -->
                  <el-table :data="formData.skipSet.collectClue.clueForms" border>
                    <el-table-column prop="linkName" label="表单类型" width="150">
                      <template #default="scope">
                        <el-select v-model="scope.row.type" placeholder="请选择类型">
                          <el-option v-for="(item, index) in clueFormsType" :key="index" :label="item.label" :value="item.value" ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="title" label="字段标题" width="200">
                      <template #default="scope">
                        <el-input v-model="scope.row.title" placeholder="请输入字段标题" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="type" label="默认值" width="200">
                      <template #default="scope">
                        <div v-if="scope.row.type === '3' || scope.row.type === '4'" >
                          <el-input v-model="scope.row.defaultValue" placeholder="单选或多选值，使用|分割。例如：男|女" />
                          <div style="font-size: 10px; color: #999;">
                            使用|分割。例如：男|女
                          </div>
                        </div>
                        <div v-else></div>
                      </template>
                    </el-table-column>
                    <el-table-column label="必填">
                      <template #default="scope">
                        <el-switch v-model="scope.row.required" inline-prompt active-value="1" inactive-value="0" active-text="是" inactive-text="否"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button link type="primary" icon="Delete" @click="handleClueFormsDelete(scope.$index)" />
                      </template>
                    </el-table-column>
                  </el-table>
                  <div style="margin-top: 20px">
                    <el-button type="primary" @click="handleClueFormsAdd">添加</el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="表单标题" prop="skipSet.collectClue.title">
              <el-input v-model="formData.skipSet.collectClue.title" placeholder="表单标题" />
            </el-form-item>
            <el-form-item label="按钮文字" prop="skipSet.collectClue.btnText">
              <el-input v-model="formData.skipSet.collectClue.btnText" placeholder="表单标题" />
            </el-form-item>
            <el-form-item label="按钮颜色" prop="skipSet.collectClue.btnColor">
              <el-color-picker v-model="formData.skipSet.collectClue.btnColor"></el-color-picker>
            </el-form-item>
          </div>
          <el-form-item label="跳转类型" prop="skipSet.type">
            <el-radio-group v-model="formData.skipSet.type">
              <el-radio v-for="(item, index) in bus_skip_set_type" :key="index" :label="item.label" :value="item.value" />
            </el-radio-group>
          </el-form-item>
          <!--获客助手-->
          <div v-if="formData.skipSet.type === '0'">
            <el-form-item label="跳转客服" prop="skipSet.linksIds">
              <!-- 第一行：下拉框 + 按钮 -->
              <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                <el-select
                  v-model="formData.skipSet.linksIds"
                  multiple
                  placeholder="请选择客服链路"
                  style="width: 240px"
                  @change="selectEmpInfo"
                >
                  <el-option-group
                    v-for="e in myCpInfos"
                    :key="e.id"
                    :label="e.corpName"
                  >
                    <el-option
                      v-for="item in e.cpLinksVoList"
                      :key="item.cpId"
                      :label="item.linkName"
                      :value="item.cpId"
                    />
                  </el-option-group>
                </el-select>
                <el-button type="primary" size="small" @click="getMyCpInfoData">加载客服</el-button>
                <!-- 第二行：提示文字（独立区块，一定会在下面） -->
                <div style="font-size: 12px; color: #999;">
                  如无法加载出客服信息时，请点击加载按钮
                </div>
              </div>
            </el-form-item>
            <el-form-item label="客服参数" prop="skipSet.linksInfos">
              <div style="width: 600px;background: #F7F7F7;padding: 20px;">
                <div style="font-size: 10px; color: #999;background-color: white;padding: 10px;">
                  加粉上限:默认无上限，系统平均分配;设置上限数值后，当日完成数值加粉 后，该员工不再进粉;次日从0开始重新计算。
                  兜底员工:推荐设置，当所有接待员工都达到设置的加粉上限后，将使用兜底 员工接待，避免用户流失。
                  <!-- 表格 -->
                  <el-table :data="formData.skipSet.linksInfos" border>
                    <el-table-column prop="linksName" label="客服名称" />
                    <el-table-column label="加粉上限">
                      <template #default="scope">
                        <el-input-number v-model="scope.row.fansLimit" :min="0" ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="兜底员工">
                      <template #default="scope">
                        <el-switch v-model="scope.row.backstop" inline-prompt active-value="1" inactive-value="0" active-text="是" inactive-text="否"/>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

            </el-form-item>
          </div>
          <!--跳转链接-->
          <div v-if="formData.skipSet.type === '1'">
            <el-form-item label="跳转链接" prop="skipSet.skipUrl">
              <el-input v-model="formData.skipSet.skipUrl" placeholder="请输入跳转链接" />
            </el-form-item>
          </div>
          <!--客服微信号-->
          <div v-if="formData.skipSet.type === '2'">
            <el-form-item label="客服微信" prop="skipSet.wxIds">
              <!-- 第一行：下拉框 + 按钮 -->
              <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                <el-select
                  v-model="formData.skipSet.wxIds"
                  multiple
                  placeholder="请选择客服微信"
                  style="width: 240px"
                  @change="selectWxInfo"
                >
                  <el-option
                    v-for="e in myWxInfos"
                    :key="e.id"
                    :value="e.id"
                    :label="e.customName + '(' + e.wxNumber + ')'"
                  />
                </el-select>
                <el-button type="primary" size="small" @click="getMyWxInfoData">加载客服</el-button>
                <!-- 第二行：提示文字（独立区块，一定会在下面） -->
                <div style="font-size: 12px; color: #999;">
                  如无法加载出客服微信信息时，请点击加载按钮
                </div>
              </div>
            </el-form-item>
            <el-form-item label="客服参数" prop="skipSet.wxInfos">
              <div style="width: 600px;background: #F7F7F7;padding: 20px;">
                <div style="font-size: 10px; color: #999;background-color: white;padding: 10px;">
                  加粉上限:默认无上限，系统平均分配;设置上限数值后，当日完成数值加粉 后，该员工不再进粉;次日从0开始重新计算。
                  兜底员工:推荐设置，当所有接待员工都达到设置的加粉上限后，将使用兜底 员工接待，避免用户流失。
                  <!-- 表格 -->
                  <el-table :data="formData.skipSet.wxInfos" border>
                    <el-table-column prop="wxName" label="客服名称" />
                    <el-table-column label="加粉上限">
                      <template #default="scope">
                        <el-input-number v-model="scope.row.fansLimit" :min="0" ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="兜底员工">
                      <template #default="scope">
                        <el-switch v-model="scope.row.backstop" inline-prompt active-value="1" inactive-value="0" active-text="是" inactive-text="否"/>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

            </el-form-item>
          </div>
          <!--小程序-->
          <div v-if="formData.skipSet.type === '3'">
            <el-form-item label="小程序" prop="skipSet.xcxIds">
              <!-- 第一行：下拉框 + 按钮 -->
              <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                <el-select
                  v-model="formData.skipSet.xcxIds"
                  placeholder="请选择小程序"
                  multiple
                  :multiple-limit="1"
                  style="width: 240px"
                >
                  <el-option
                    v-for="e in myXcxInfos"
                    :key="e.id"
                    :value="e.id"
                    :label="e.name + '(' + e.customName + ')'"
                  />
                </el-select>
                <el-button type="primary" size="small" @click="getMyXcxInfoData">加载小程序</el-button>
                <!-- 第二行：提示文字（独立区块，一定会在下面） -->
                <div style="font-size: 12px; color: #999;">
                  如无法加载出小程序信息时，请点击加载按钮
                </div>
              </div>
            </el-form-item>
          </div>
          <!--企微互通-->
          <div v-if="formData.skipSet.type === '4'">
            <el-form-item label="企微互通" prop="skipSet.linksIds">
              <!-- 第一行：下拉框 + 按钮 -->
              <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                <el-select
                  v-model="formData.skipSet.wxHtUserIds"
                  multiple
                  placeholder="请选择互通客服"
                  style="width: 240px"
                  @change="selectWxHtUserInfo"
                >
                  <el-option-group
                    v-for="e in myCpHtInfos"
                    :key="e.id"
                    :label="e.corpName"
                  >
                    <el-option
                      v-for="item in e.cpHtUserVoList"
                      :key="item.id"
                      :label="item.nameRemark"
                      :value="item.id"
                    />
                  </el-option-group>
                </el-select>
                <el-button type="primary" size="small" @click="getMyCpHtData">加载客服</el-button>
                <!-- 第二行：提示文字（独立区块，一定会在下面） -->
                <div style="font-size: 12px; color: #999;">
                  如无法加载出客服信息时，请点击加载按钮
                </div>
              </div>
            </el-form-item>
            <el-form-item label="客服参数" prop="skipSet.wxHtUsers">
              <div style="width: 600px;background: #F7F7F7;padding: 20px;">
                <div style="font-size: 10px; color: #999;background-color: white;padding: 10px;">
                  加粉上限:默认无上限，系统平均分配;设置上限数值后，当日完成数值加粉 后，该员工不再进粉;次日从0开始重新计算。
                  兜底员工:推荐设置，当所有接待员工都达到设置的加粉上限后，将使用兜底 员工接待，避免用户流失。
                  <!-- 表格 -->
                  <el-table :data="formData.skipSet.wxHtUsers" border>
                    <el-table-column prop="nameRemark" label="客服名称" />
                    <el-table-column label="加粉上限">
                      <template #default="scope">
                        <el-input-number v-model="scope.row.fansLimit" :min="0" ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="兜底员工">
                      <template #default="scope">
                        <el-switch v-model="scope.row.backstop" inline-prompt active-value="1" inactive-value="0" active-text="是" inactive-text="否"/>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

            </el-form-item>
          </div>
        </el-card>

        <!--      广告回传-->
        <el-card class="box-card" v-if="formData.adverBack?.platformInfo">
          <template #header>
            <div class="card-header">
              <span>广告回传</span>
            </div>
          </template>
          <el-form-item label="回传平台" prop="adverBack.platformInfo.type">
            <el-radio-group v-model="formData.adverBack.platformInfo.type">
              <el-radio v-for="dict in adver_back_type" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="不回传APP" v-if="formData.adverBack.platformInfo.type === '1'" prop="adverBack.platformInfo.douYinNotBack">
            <!--          等于抖音才显示-->
            <el-checkbox-group v-model="formData.adverBack.platformInfo.douYinNotBack">
              <el-checkbox v-for="dict in adver_back_douyin" :key="dict.value" :value="dict.value" :label="dict.label" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="Token" prop="adverBack.platformInfo.baiDuToken" v-if="formData.adverBack.platformInfo.type === '3'">
            <!--          等于百度才显示-->
            <el-input v-model="formData.adverBack.platformInfo.baiDuToken" placeholder="请输入百度Token" style="width: 500px"/>
          </el-form-item>
          <el-form-item label="事件设置" prop="adverBack.adverBackEvent">
            <div style="width: 700px;background: #F7F7F7;padding: 20px;">
              <div style="font-size: 10px; color: #000000;background-color: white;padding: 10px;">
                加请选择用户转化链路上的各类事件，按链路回传将更有利于优化广告投放效果了解详情
                <!-- 表格 -->
                <el-table :data="formData.adverBack.adverBackEvent" border>
                  <el-table-column prop="userAction" label="用户行为">
                    <template #default="scope">
                      <dict-tag :options="adver_back_user_action" :value="scope.row.userAction" />
                    </template>
                  </el-table-column>
                  <el-table-column label="事件名称">
                    <template #default="scope">
                      <el-select v-model="scope.row.event" placeholder="请选择事件">
                        <el-option v-for="(item, index) in adver_back_event" :key="index" :label="item.label" :value="item.value" ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="remarks" label="用户行为说明" width="300">
                    <template #default="scope">
                      <span style="font-size: 12px">{{scope.row.remarks}}</span>
                    </template>
                  </el-table-column>/>
                </el-table>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="回传比例" prop="adverBackRatio">
            <el-input-number v-model="formData.adverBackRatio" :min="1" :max="100">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
            <!-- 第二行：提示文字（独立区块，一定会在下面） -->
            <div style="font-size: 12px; color: #999;">
              设置100%表示全部回传。如设置70%就回传70条
            </div>
          </el-form-item>
          <el-form-item label="自动回传" prop="adverBackAuto">
            <el-radio-group v-model="formData.adverBackAuto">
              <el-radio value="0">自动回传</el-radio>
              <el-radio value="1">手动回传</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>
      </el-form>
    </div>
    <div class="footer-btns">
      <div class="footer-btns-content">
        <el-button :loading="buttonLoading" type="primary" @click="handleSave">保 存</el-button>
      </div>
    </div>
    <PhonePreview :contentComponent="previewComponent":component-props="currentProps" :background-color="previewBackgroundColor"/>
  </div>
</template>

<script setup name="JqtSpreadLink" lang="ts">
import { AdverBack, JqtSpreadLinkForm, PageModeContent } from '@/api/bus/jqtSpreadLink/types';
import ImageMode, { ImageModeVo } from '@/views/bus/jqtSpreadLink/mode/imageMode.vue';
import ImageTextMode, { ImageTextModeVo } from '@/views/bus/jqtSpreadLink/mode/imageTextMode.vue';
import DialogMode, { DialogModeVo } from '@/views/bus/jqtSpreadLink/mode/dialogMode.vue';
import DialogSetMode, { DialogModeSetVo } from '@/views/bus/jqtSpreadLink/mode/dialogSetMode.vue';
import imageHtmlTemplate from '@/views/bus/jqtSpreadLink/preview/imageHtmlTemplate.vue'
import imageTextHtmlTemplate from '@/views/bus/jqtSpreadLink/preview/imageTextHtmlTemplate.vue'
import dialogMode1Template from '@/views/bus/jqtSpreadLink/preview/dialogMode1Template.vue'
import dialogMode2Template from '@/views/bus/jqtSpreadLink/preview/dialogMode2Template.vue'
import dialogMode3Template from '@/views/bus/jqtSpreadLink/preview/dialogMode3Template.vue'
import dialogMode4Template from '@/views/bus/jqtSpreadLink/preview/dialogMode4Template.vue'
import keywordTemplate from '@/views/bus/jqtSpreadLink/preview/keywordTemplate.vue'
import KeywordMode from '@/views/bus/jqtSpreadLink/mode/keywordMode.vue';
import KeywordSetMode from '@/views/bus/jqtSpreadLink/mode/keywordSetMode.vue';
import { getMyCpInfo } from '@/api/bus/jqtCpInfo';
import { JqtCpInfoVO } from '@/api/bus/jqtCpInfo/types';
import api from '@/api/system/user';
import { addJqtSpreadLink, getJqtSpreadLink, updateJqtSpreadLink } from '@/api/bus/jqtSpreadLink';
import { addClient, updateClient } from '@/api/system/client';
import { getMyWxInfo } from '@/api/bus/jqtWxInfo';
import { JqtWxInfoVO } from '@/api/bus/jqtWxInfo/types';
import { JqtXcxInfoVO } from '@/api/bus/jqtXcxInfo/types';
import { getMyXcxInfo } from '@/api/bus/jqtXcxInfo';
import { getMyCpHtInfo } from '@/api/bus/jqtCpHtInfo';
import { JqtCpHtInfoVO } from '@/api/bus/jqtCpHtInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const { sys_normal_disable,bus_spread_link_page_mode } = toRefs<any>(proxy?.useDict('sys_normal_disable','bus_spread_link_page_mode'));
const { adver_back_type,adver_back_douyin,adver_back_user_action,adver_back_event,bus_skip_set_type } = toRefs<any>(proxy?.useDict('adver_back_type','adver_back_douyin','adver_back_user_action','adver_back_event','bus_skip_set_type'));

const buttonLoading = ref(false);

const previewComponent = ref(null);
// 传递给组件的 props
const currentProps = ref({});
// 预览背景色
const previewBackgroundColor = ref<string>('');
//默认颜色
const defaultColor = ref('#4173ff');
const formRef = ref<ElFormInstance>();
const initFormData: JqtSpreadLinkForm = {
  id: undefined,
  linkName: undefined,
  spreadUrl: undefined,
  status: undefined,
  pageMode: undefined,
  pageModeContent: {},
  skipSet: {},
  adverBack: undefined,
  adverBackRatio: undefined,
  adverBackAuto: undefined,
  remark: undefined,
}
const formData = reactive<JqtSpreadLinkForm>({
  ...initFormData
});

const rules = {
  linkName: [
    { required: true, message: "落地页名称不能为空", trigger: "blur" }
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: "change" }
  ],
  pageMode: [
    { required: true, message: "页面模式不能为空", trigger: "change" }
  ],
  // 跳转模式
  'skipSet.mode': [
    { required: true, message: '请选择跳转模式', trigger: 'change' }
  ],
  // 跳转类型
  'skipSet.type': [
    { required: true, message: '请选择跳转类型', trigger: 'change' }
  ],
  // 当 mode === '1' 时，收集线索相关字段必填
  'skipSet.collectClue.title': [
    { required: true, message: '请输入表单标题', trigger: 'blur' },
    { min: 1, max: 50, message: '标题长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  'skipSet.collectClue.btnText': [
    { required: true, message: '请输入按钮文字', trigger: 'blur' },
    { min: 1, max: 20, message: '按钮文字长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  'skipSet.collectClue.btnColor': [
    { required: true, message: '请选择按钮颜色', trigger: 'change' }
  ],
  'skipSet.collectClue.clueForms': [
    { required: true, message: '请添加线索', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一个表单字段'));
        } else {
          const invalid = value.some(item => !item.type || !item.title);
          if (invalid) {
            callback(new Error('线索表单填写不完整'));
          } else {
            callback();
          }
        }
      },
      trigger: 'change'
    }
  ],
  // 当 type === '1' 时，跳转链接必填
  'skipSet.skipUrl': [
    { required: true, message: '请输入跳转链接', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '1') {
          if (!value) {
            callback(new Error('请输入跳转链接'));
          } else if (!/^https?:\/\/.+/i.test(value)) {
            callback(new Error('请输入有效的 URL 地址，以 http:// 或 https:// 开头'));
          } else {
            callback();
          }
        } else {
          callback(); // 不需要验证
        }
      },
      trigger: 'blur'
    }
  ],

  // 客服链路选择（当 type === '0' 时必填）
  'skipSet.linksIds': [
    { required: true, message: '请选择客服链路', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '0') {
          if (!value || value.length === 0) {
            callback(new Error('请选择至少一个客服链路'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],

  // 客服参数 linksInfos（当 type === '0' 且 linksIds 有值时）
  'skipSet.linksInfos': [
    { required: true, message: '请选择客服链路', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '0') {
          if (!value || value.length === 0) {
            callback(new Error('客服参数未生成，请先选择客服'));
          } else {
            // const hasBackstop = value.some(item => item.backstop === '1');
            // if (!hasBackstop) {
            //   callback(new Error('请至少设置一个兜底员工，防止用户流失'));
            // } else {
            //   callback();
            // }
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  // 客服链路选择（当 type === '2' 时必填）
  'skipSet.wxIds': [
    { required: true, message: '请选择客服微信', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '2') {
          if (!value || value.length === 0) {
            callback(new Error('请选择至少一个客服微信'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  // 客服链路选择（当 type === '3' 时必填）
  'skipSet.xcxIds': [
    { required: true, message: '请选择小程序', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '3') {
          if (!value || value.length === 0) {
            callback(new Error('请选择至少一个小程序'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],

  // 企微互通用户选择（当 type === '0' 时必填）
  'skipSet.wxHtUserIds': [
    { required: true, message: '请选择企业互通用户', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '0') {
          if (!value || value.length === 0) {
            callback(new Error('请选择至少一个互通客服'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],

  // 客服参数 wxHtUsers（当 type === '4' 且 wxHtUserIds 有值时）
  'skipSet.wxHtUsers': [
    { required: true, message: '请选择企业互通用户', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.skipSet.type === '0') {
          if (!value || value.length === 0) {
            callback(new Error('客服参数未生成，请先选择客服'));
          } else {
            // const hasBackstop = value.some(item => item.backstop === '1');
            // if (!hasBackstop) {
            //   callback(new Error('请至少设置一个兜底员工，防止用户流失'));
            // } else {
            //   callback();
            // }
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  // 回传平台类型：必选
  'adverBack.platformInfo.type': [
    { required: true, message: '请选择回传平台', trigger: 'change' }
  ],

  // 百度 Token：仅当平台为百度（type === '3'）时必填
  'adverBack.platformInfo.baiDuToken': [
    { required: true, message: '请输入百度 Token', trigger: 'change' },
  ],


  adverBackRatio: [
    { required: true, message: "广告回传比例", trigger: "blur" }
  ],
  adverBackAuto: [
    { required: true, message: "广告回传模式不能为空", trigger: "blur" }
  ]
};


//选择的页面模式
const selectPageMode = ref(null);
const dataId = ref(null);
onMounted(async () => {
  //初始化回传设置
  await initAdverBack();
  //初始化跳转设置
  await initSkipSet();
  //获取企业信息
  await getMyCpInfoData();
  //获取微信信息
  await getMyWxInfoData();
  //获取小程序信息
  await getMyXcxInfoData();
  //获取企微互通信息
  await getMyCpHtData();
  const mode = route.params && (route.params.mode as string)
  const id = route.params && (route.params.id as string | number)

  watchEffect(() => {
    const value = bus_spread_link_page_mode.value;
    if (Array.isArray(value) && value.length > 0) {
      initMode(mode); // 自动触发
      if(id){
        initData(id);
      }
    }
  });
});
/**
 * 初始化页面模式
 * @param mode
 */
const initMode = async (mode) =>{
  selectPageMode.value = await bus_spread_link_page_mode.value.find(item=>item.value === mode);
  formData.pageMode = mode;
}
/**
 * 初始化数据
 * @param id
 */
const initData = async (id: string | number) =>{
  const res = await getJqtSpreadLink(id);
  Object.assign(formData, res.data);
  // 抖音不回传APP初始化数据
  if(!formData.adverBack.platformInfo.douYinNotBack){
    formData.adverBack.platformInfo.douYinNotBack = [];
  }
  dataId.value = id;
}
/**
 * 初始化广告回传
 */
const initAdverBack = async () => {
  formData.adverBack = {
    platformInfo: {
      type: '1',
      douYinNotBack: undefined,
      baiDuToken: undefined,
    },
    adverBackEvent:[]
  }
  //好友申请
  formData.adverBack.adverBackEvent.push({ userAction: '0', event: '0', eventName: '不回传', remarks:'用户通过获客链接发送添加好友请求' })
  //成功添加好友
  formData.adverBack.adverBackEvent.push({ userAction: '1', event: '0', eventName: '不回传', remarks:'用户通过获客链接成功添加好友' })
  //首次开口
  formData.adverBack.adverBackEvent.push({ userAction: '2', event: '0', eventName: '不回传', remarks:'用户通过获客链接添加好友后，发送首条信息' })
  //3次开口
  formData.adverBack.adverBackEvent.push({ userAction: '3', event: '0', eventName: '不回传', remarks:'用户通过获客链接添加好友后，发送3条信息' })
  //5次开口
  formData.adverBack.adverBackEvent.push({ userAction: '4', event: '0', eventName: '不回传', remarks:'用户通过获客链接添加好友后，发送5条信息' })
  //10次开口
  formData.adverBack.adverBackEvent.push({ userAction: '5', event: '0', eventName: '不回传', remarks:'用户通过获客链接添加好友后，发送10条信息' })
};
/**
 * 初始化跳转设置
 */
const initSkipSet = async () => {
  formData.skipSet = {
    mode: '0',
    collectClue: {
      clueForms: [],
      btnText: '点击提交',
      btnColor: defaultColor.value,
      title: '填写信息，领取方案',
    },
    type: '0',
    linksIds: [],
    linksInfos: [],
    skipUrl: undefined,
    wxIds: [],
    wxInfos:[],
    xcxIds: [],
    wxHtUserIds: [],
    wxHtUsers: [],
  };
};

/**
 * 获取当前选择的页面模式
 * @param pageMode
 */
const getSelectPageMode = () =>{
  selectPageMode.value = bus_spread_link_page_mode.value.find(item=>item.value === formData.pageMode);
}

/**
 * 页面模式内容变化预览
 */
watch(
  () => formData.pageModeContent,
  async (newValue: PageModeContent) => {
    if (newValue) {
      currentProps.value = newValue;
      previewBackgroundColor.value = '';
      console.log('newValue', newValue);
      // 图片模式
      if(formData.pageMode === '1001'){
        previewComponent.value = imageHtmlTemplate;
      }else if(formData.pageMode === '1002'){
        // 图文交互模式
        previewComponent.value = imageTextHtmlTemplate;
      }else if(formData.pageMode === '1003'){
        // 问答模式
        //风格类型 0.模板一(问答跟随) 1.模板二(问答悬浮) 2.模板三(内容跟随+按钮在底部) 3.模板四(内容+按钮跟随)
        if(newValue?.dialog?.type === '0'){
          previewComponent.value = dialogMode1Template;
        }else if(newValue.dialog.type === '1'){
          previewComponent.value = dialogMode2Template;
        }else if(newValue.dialog.type === '2'){
          previewComponent.value = dialogMode3Template;
        }else if(newValue.dialog.type === '3'){
          previewComponent.value = dialogMode4Template;
        }
        previewBackgroundColor.value = '#f5f5f5';
      }else if(formData.pageMode === '1004'){
        // 关键词回复模式
        previewComponent.value = keywordTemplate;
        previewBackgroundColor.value = '#f5f5f5';
      }
    }
  }, { deep: true, immediate: true }
);

// 所有子组件的 ref
const imageModeRef = ref(null);//图片模式
const imageTextModeRef = ref(null);//图文交互模式
const dialogModeRef = ref(null);//问答模式
const dialogSetModeRef = ref(null);//问答模式设置
const keywordModeRef = ref(null);//关键词模式
const keywordSetModeRef = ref(null);//关键词模式设置
/**
 * 保存按钮
 */
const handleSave = async () => {
  try {
    await formRef.value?.validate();

    // 根据 pageMode 判断需要校验哪些子组件
    if (formData.pageMode === '1001') {
      const ref = unref(imageModeRef);
      if (ref && typeof ref.validateForm === 'function') {
        await ref.validateForm();
      }
    } else if (formData.pageMode === '1002') {
      const ref = unref(imageTextModeRef);
      if (ref && typeof ref.validateForm === 'function') {
        await ref.validateForm();
      }
    } else if (formData.pageMode === '1003') {
      // 🔥 问答模式：需要同时校验两个组件
      const dialogRef = unref(dialogModeRef);
      const dialogRefSet = unref(dialogSetModeRef);

      // 依次校验，可改为 Promise.all 并行（如果 validateForm 支持异步并行）
      if (dialogRef && typeof dialogRef.validateForm === 'function') {
        await dialogRef.validateForm();
      }
      if (dialogRefSet && typeof dialogRefSet.validateForm === 'function') {
        await dialogRefSet.validateForm();
      }
    } else if (formData.pageMode === '1004') {
      // 🔥 关键词模式：需要同时校验两个组件
      const keywordRef = unref(keywordModeRef);
      const keywordRefSet = unref(keywordSetModeRef);

      // 依次校验，可改为 Promise.all 并行（如果 validateForm 支持异步并行）
      if (keywordRef && typeof keywordRef.validateForm === 'function') {
        await keywordRef.validateForm();
      }
      if (keywordRefSet && typeof keywordRefSet.validateForm === 'function') {
        await keywordRefSet.validateForm();
      }
    }

    buttonLoading.value = true;
    // 所有校验通过
    console.log('✅ 所有校验通过，提交数据:', formData);
    if(dataId.value){
      await updateJqtSpreadLink(formData).finally(() => (buttonLoading.value = false));
    }else{
      await addJqtSpreadLink(formData).finally(() => (buttonLoading.value = false));
    }
    proxy?.$modal.msgSuccess('保存成功');
    proxy?.$tab.closePage();
  } catch (error: any) {
    console.warn('❌ 表单校验失败:', error.message);
    proxy?.$modal.msgError(error.message || '基础表单填写不完整');
  }

};
const myCpInfos = ref<JqtCpInfoVO[]>([]);
/**
 * 获取我的企业信息
 */
const getMyCpInfoData = async () => {
  const res = await getMyCpInfo();
  myCpInfos.value = res.data;
};

const myWxInfos = ref<JqtWxInfoVO[]>([]);
/**
 * 获取我的客服微信信息
 */
const getMyWxInfoData = async () => {
  const res = await getMyWxInfo();
  myWxInfos.value = res.data;
};
const myXcxInfos = ref<JqtXcxInfoVO[]>([]);
/**
 * 获取我的小程序信息
 */
const getMyXcxInfoData = async () => {
  const res = await getMyXcxInfo();
  myXcxInfos.value = res.data;
};
const myCpHtInfos = ref<JqtCpHtInfoVO[]>([]);
/**
 * 获取我的企微互通企业
 */
const getMyCpHtData = async () => {
  const res = await getMyCpHtInfo();
  myCpHtInfos.value = res.data;
};

/**
 * 选择获客员工信息
 * @param value
 */
const selectEmpInfo = async (data:[]) => {
  formData.skipSet.linksInfos = [];
  // 遍历传入的 id 列表（即 cpId）
  data.forEach(id => {
    // 遍历 myCpInfos 中的每个企业
    myCpInfos.value.forEach(corp => {
      // 在 cpLinksVoList 中查找是否有 cpId 匹配的项
      const matchedLink = corp.cpLinksVoList.find(link => link.cpId === id);
      if (matchedLink) {
        const e = {
          linksId: matchedLink.id,//链接ID
          linksName: matchedLink.linkName,//链接名称
          fansLimit: 999,// 默认粉丝数限制为999
          backstop: '0',// 默认不是兜底
        }
        formData?.skipSet?.linksInfos.push(e);
      }
    });
  });
};

/**
 * 选择客服微信信息
 * @param value
 */
const selectWxInfo = async (data:[]) => {
  formData.skipSet.wxInfos = [];
  // 遍历传入的 id 列表（即 cpId）
  data.forEach(id => {
    // 遍历 查找是否有 Id 匹配的项
    const wxInfo = myWxInfos.value.find(e => e.id === id);
    if(wxInfo){
      const e = {
        wxId: wxInfo.id,//链接ID
        wxName: wxInfo.customName + '(' + wxInfo.wxNumber + ')',//链接名称
        fansLimit: 999,// 默认粉丝数限制为999
        backstop: '0',// 默认不是兜底
      }
      formData?.skipSet?.wxInfos.push(e);
    }
  });
};


/**
 * 选择企微互通信息
 * @param value
 */
const selectWxHtUserInfo = async (data:[]) => {
  formData.skipSet.wxHtUsers = [];
  // 遍历传入的 id 列表（即 cpId）
  data.forEach(id => {
    // 遍历 myCpInfos 中的每个企业
    myCpHtInfos.value.forEach(corp => {
      // 在 cpHtUserVoList 中查找是否有 cpHtId 匹配的项
      const matchedUser = corp.cpHtUserVoList.find(link => link.id === id);
      if (matchedUser) {
        const e = {
          htUserId: matchedUser.id,//链接ID
          nameRemark: matchedUser.nameRemark,//链接名称
          fansLimit: 999,// 默认粉丝数限制为999
          backstop: '0',// 默认不是兜底
        }
        formData?.skipSet?.wxHtUsers.push(e);
      }
    });
  });
};
//线索表单类型
const clueFormsType = [
  {
    value: '0',
    label: '手机号',
  },
  {
    value: '1',
    label: '文本',
  },
  {
    value: '2',
    label: '数字',
  },
  {
    value: '3',
    label: '单项选择',
  },
  {
    value: '4',
    label: '多项选择',
  },

];
/**
 * 添加线索表单
 */
const handleClueFormsAdd = () => {
  formData.skipSet.collectClue.clueForms.push({
    type: '',
    title: '',
    defaultValue: '',
    required: '1',
  });
};
/**
 * 删除线索表单
 * @param index
 */
const handleClueFormsDelete = (index: number) => {
  formData.skipSet.collectClue.clueForms.splice(index, 1);
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px; /* 卡片底部间距 */
  border-radius: 10px;
}
.box-card:last-child {
  margin-bottom: 50px; /* 确保最后一个 box-card 不会被 footer-btns 遮挡 */
}

.footer-btns {
  width: 100%;
  height: 50px;
  position: fixed;      /* 固定定位，实现悬浮 */
  bottom: 0;            /* 距离底部 0px，可根据需要调整 */
  left: 50%;            /* 水平居中：先移到父级50%位置 */
  transform: translateX(-50%); /* 再向左偏移自身宽度的一半 */
  z-index: 1000;        /* 确保悬浮在其他内容之上 */
  background-color: #fff; /* 可选：背景色，防止内容穿透 */
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1); /* 可选：添加阴影，增强悬浮感 */
  display: flex;        /* 添加此行，使 footer-btns 成为 Flex 容器 */
  justify-content: center; /* 水平居中 */
  align-items: center;  /* 垂直居中 */
}
</style>
